/*
 * The MIT License (MIT)
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */

use std::thread::sleep;

use napi::bindgen_prelude::*;
use napi::{oh_log_info, JsNumber};
use napi_derive::napi;

struct DelaySum(u32, u32);

#[napi]
impl napi::Task for DelaySum {
  type Output = u32;
  type JsValue = u32;

  fn compute(&mut self) -> Result<Self::Output> {
    sleep(std::time::Duration::from_millis(100));
    Ok(self.0 + self.1)
  }

  fn resolve(&mut self, _env: napi::Env, output: Self::Output) -> Result<Self::JsValue> {
    Ok(output)
  }
}

#[napi]
fn without_abort_controller(a: u32, b: u32) -> AsyncTask<DelaySum> {
  AsyncTask::new(DelaySum(a, b))
}

#[napi]
fn with_abort_controller(a: u32, b: u32, signal: AbortSignal) -> AsyncTask<DelaySum> {
  AsyncTask::with_signal(DelaySum(a, b), signal)
}

struct AsyncTaskVoidReturn {}

#[napi]
impl Task for AsyncTaskVoidReturn {
  type JsValue = ();
  type Output = ();

  fn compute(&mut self) -> Result<Self::Output> {
    Ok(())
  }

  fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue> {
    Ok(output)
  }
}

#[napi]
fn async_task_void_return() -> AsyncTask<AsyncTaskVoidReturn> {
  AsyncTask::new(AsyncTaskVoidReturn {})
}

struct AsyncTaskOptionalReturn {}

#[napi]
impl Task for AsyncTaskOptionalReturn {
  type JsValue = Option<u32>;
  type Output = ();

  fn compute(&mut self) -> Result<Self::Output> {
    Ok(())
  }

  fn resolve(&mut self, _env: Env, _: Self::Output) -> Result<Self::JsValue> {
    Ok(None)
  }
}

#[napi]
fn async_task_optional_return() -> AsyncTask<AsyncTaskOptionalReturn> {
  AsyncTask::new(AsyncTaskOptionalReturn {})
}

fn task_sum(index: u32) -> u32 {
  let mut sum = 0;
  for i in 0..index {
    sum += i;
  }

  sum
}

struct AsyncSum {
  input: u32,
}

#[napi]
impl Task for AsyncSum {
  type Output = u32;
  type JsValue = JsNumber;

  fn compute(&mut self) -> Result<Self::Output> {
    Ok(task_sum(self.input))
  }

  fn resolve(&mut self, env: Env, output: u32) -> Result<Self::JsValue> {
    env.create_uint32(output)
  }

  fn finally(&mut self, _env: Env) -> Result<()> {
    oh_log_info!("in AsyncSum finally");
    Ok(())
  }
}

#[napi]
fn async_sum(input: u32) -> AsyncTask<AsyncSum> {
  AsyncTask::new(AsyncSum { input })
}

struct AsyncFailed;

impl Task for AsyncFailed {
  type Output = u32;
  type JsValue = JsNumber;

  fn compute(&mut self) -> Result<Self::Output> {
    let err = Error::new(Status::Cancelled, "failed to call compute");
    Err(err)
  }

  fn resolve(&mut self, env: Env, output: u32) -> Result<Self::JsValue> {
    env.create_uint32(output)
  }

  fn reject(&mut self, _env: Env, err: Error) -> Result<Self::JsValue> {
    oh_log_info!("in AsyncSum reject");
    Err(err)
  }

  fn finally(&mut self, _env: Env) -> Result<()> {
    oh_log_info!("in AsyncSum finally");
    Ok(())
  }
}

#[napi]
fn async_failed() -> AsyncTask<AsyncFailed> {
  AsyncTask::new(AsyncFailed)
}
